﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using SanJ.FreeCare.EntityFrameworkCore;
using SanJ.FreeCare.Medications;


namespace SanJ.FreeCare.Applets
{
    public abstract class EFAppletRepository : EFAppletRepositoryBase, IAppletRepository
    {
        public EFAppletRepository(IDbContextProvider<FreeCareDbContext> dbContextProvider) 
            : base(dbContextProvider)
        {
        }

        public async Task<long> GetCountAsync(string filter, CancellationToken cancellationToken = default)
        {
            var query = ApplyFilter((await GetDbSetAsync()), filter);
            return await query.LongCountAsync(GetCancellationToken(cancellationToken));
        }

        private IQueryable<Applet> ApplyFilter(IQueryable<Applet> query, string filter)
        {
            return query.WhereIf(!string.IsNullOrWhiteSpace(filter), e => e.Name.Contains(filter!) || e.Spell.Contains(filter!));

        }


        public async Task<List<Applet>> GetPageLisAsync(string filter, string sorting, int maxResultCount = int.MaxValue, int skipCount = 0, CancellationToken cancellationToken = default)
        {
            var query = ApplyFilter((await GetDbSetAsync()), filter);

            query = query.OrderBy(string.IsNullOrWhiteSpace(sorting) ? MedicationConsts.GetDefaultSorting(false) : sorting);
            return await query.PageBy(skipCount, maxResultCount).ToListAsync(cancellationToken);
        }
    }
}
